(function () {
    var $page = $('.page-buydemand'),
        Dialog = require('wap_common:widget/ui/dialog/dialog.js').Dialog,
        util = require('wap_common:widget/ui/libs/util.js').util,
        dialog = new Dialog({
            autoClose:true
        }),
        $previewBlock = $page.find('.preview-block'),
        $confirmBlock = $page.find('.confirm-block'),
        $loadingBlock = $page.find('.loading-block'),
        $successBlock = $page.find('.success-block'),
        $failBlock = $page.find('.fail-block'),
        $timeoutBlock = $page.find('.timeout-block'),
        $iconsBlock = $page.find('.block2 li'),
        $icons = $iconsBlock.find('.icon'),
        coupon_id, coupon_type, coupon_amount = 0, trade_id, buy_amount,
        data = P.data('data'),
        $iconI = $page.find('.buy-form .form-line1 .icon'),
        count = 0, interval;

    $iconsBlock.bind('touchstart', function () {
        $icons.removeClass('active');
        var $icon = $(this).find('.icon');
        $icon.toggleClass('active');
        coupon_id = $icon.attr('data-id');
        coupon_type = $icon.attr('data-type');
        coupon_amount = ($icon.attr('data-amount') ? $icon.attr('data-amount') : 0);
    });
    $iconI.bind('touchstart', function () {
        dialog.show('<div style="text-align: left;word-spacing: 3px">可购份额为您当前在线上可以购买的最大额度。它等于当前线上剩余可购买的活期份额和您的剩余可购份额的最小值。</div>')
    });
    $page.find('.btn-next').bind('touchstart', function () {
        if ($(this).hasClass('btn-main')) {
            var amount = buy_amount = $.trim($page.find('.amount').val());
            if (parseInt(amount) <= 0 || !/^\d+$/.test(amount)) {
                dialog.show("购买金额必须为大于0的整数");
                return false;
            }
            if (parseFloat(amount) > parseFloat(data['amount']) + parseFloat(coupon_amount)) {
                dialog.show("购买金额超过账户可用余额");
                return false;
            }
            if (parseFloat(amount) > parseFloat(data['credit_plat_buy']) || parseFloat(amount) > parseFloat(data['available_amount'])) {
                dialog.show('您的购买金额大于您的可够份额');
                return false;
            }
            $(this).addClass('btn-disable').removeClass('btn-main');
            initConfirm();
        }
    });
    var initConfirm = function () {
        $confirmBlock.find('.buy-amount').text(util.formatAmount(buy_amount, 2));
        $confirmBlock.find('.actual-amount').text(util.formatAmount(buy_amount - (coupon_amount ? coupon_amount : 0), 2));
        if (coupon_id && coupon_type) {
            $previewBlock.find('.coupon_info').show();
            $previewBlock.find('.coupon_info').find('.coupon_info_amount').text(util.formatAmount(coupon_amount));
        } else {
            $previewBlock.find('.coupon_info').hide();
        }
        $previewBlock.hide();
        $confirmBlock.show();
    };

    $page.find('.btn-purchasing').bind('touchstart', function () {
        if ($(this).hasClass('btn-main')) {
            var amount = buy_amount;
            var coupon_amount = parseFloat(coupon_amount);

            if (parseInt(amount) <= 0 || !/^\d+$/.test(amount)) {
                dialog.show("购买金额必须为大于0的整数");
                return false;
            }

            if (amount > data['usable_amount'] + coupon_amount) {
                dialog.show("账户余额不足，请到电脑版充值。");
                return false;
            }
            if (parseFloat(amount) > data['credit_plat_buy'] || parseFloat(amount) > data['available_amount']) {
                dialog.show('您的购买金额大于您的可够份额');
                return false;
            }

            $(this).addClass('btn-disable').removeClass('btn-main');
            $.post('/wap/purchasing', {
                amount: amount,
                coupon_type: (coupon_type ? coupon_type : ''),
                coupon_id: (coupon_id ? coupon_id : ''),
                pid: 1
            }, function (ret, status) {
                if (ret.error_no == 0) {
                    $loadingBlock.show();
                    $confirmBlock.hide();
                    trade_id = ret.data;
                    setTimeout(function () {
                        interval = setInterval(function () {
                            refresh();
                            if (count++ >= 30) {
                                clearInterval(interval);
                            }
                        }, 2000);
                    }, 3000);
                    refresh();
                } else {
                    dialog.show(ret.error_message);
                }
            }, 'json');
        }
    });
    function refresh() {
        $.get('/user/gettradestatus', {
            'serial_id': trade_id
        }, function (ret, st) {
            if (ret.error_no == 0) {
                var status = ret.data.tradeItem.status;
                if (status == 2) {
                    $loadingBlock.hide();
                    $failBlock.show();
                    clearInterval(interval);
                } else if (status == 1) {
                    $loadingBlock.hide();
                    $successBlock.show().find('.amount').text(parseInt(ret.data.tradeItem.amount));
                    clearInterval(interval);
                } else {
                    if (count > 10) {
                        $loadingBlock.hide();
                        $timeoutBlock.show();
                        clearInterval(interval);
                    }
                }
            }
        }, 'json');
    }

    $page.find('.trade-log-btn').bind('touchstart', function () {
        location.href = '/wap/tradelog';
    });
    $page.find('.wallet-btn').bind('touchstart', function () {
        location.href = '/wap/wallet';
    });

})();